import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:meco/common/index.dart';
import 'dart:io';

import 'index.dart';

class NotificationPage extends GetView<NotificationController> {
  const NotificationPage({super.key});

  // 主视图
  Widget _buildView() {
    return Stack(
      children: [
        // 背景
        Positioned.fill(child: Image.asset(Images.startBg, fit: BoxFit.cover)),

        // 内容
        Column(
          children: [
            SizedBox(height: 50.h),

            Padding(
              padding: EdgeInsets.symmetric(horizontal: 20.w),
              child: Align(
                alignment: Alignment.topLeft,
                child: GestureDetector(
                  onTap: () {
                    Get.back();
                  },
                  child: Icon(IconFontIcons.iconBack, color: Colors.white),
                ),
              ),
            ),
            SizedBox(height: 26.h),

            // 自定义TabBar
            _buildTabBar(),

            // Tab内容区域
            Expanded(
              child: Obx(() {
                if (controller.isLoading.value) {
                  return Center(
                    child: CircularProgressIndicator(color: Colors.white),
                  );
                }

                return TabBarView(
                  controller: controller.tabController,
                  physics: const ClampingScrollPhysics(),
                  children: [
                    // 私聊内容
                    _buildPrivateChatList(),

                    // 群聊内容
                    _buildGroupChatList(),

                    // 关注内容
                    _buildFollowList(),

                    // 粉丝内容
                    _buildFanList(),
                  ],
                );
              }),
            ),
          ],
        ),
      ],
    );
  }

  // 构建TabBar
  Widget _buildTabBar() {
    return Container(
      height: 40.h,
      alignment: Alignment.center,
      child: AnimatedBuilder(
        animation: controller.tabController.animation!,
        builder: (context, child) {
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildTabItem(0, 'Private Chat'),
              _buildTabItem(1, 'Group Chat'),
              _buildTabItem(2, 'follow'),
              _buildTabItem(3, 'fan'),
            ],
          );
        },
      ),
    );
  }

  // 构建单个Tab项
  Widget _buildTabItem(int index, String title) {
    // 获取当前动画值，用于平滑过渡
    double animationValue =
        controller.tabController.animation?.value ??
        controller.tabController.index.toDouble();

    // 计算选中状态的程度 (0.0 到 1.0)
    double selectedPercent =
        1.0 - (animationValue - index).abs().clamp(0.0, 1.0);

    // 混合颜色
    final Color textColor =
        Color.lerp(
          const Color(0xFFADC5E8), // 未选中颜色
          Colors.white, // 选中颜色
          selectedPercent,
        )!;

    // 混合字重
    final FontWeight fontWeight =
        selectedPercent > 0.5 ? FontWeight.w700 : FontWeight.w500;

    return GestureDetector(
      onTap: () => controller.tabController.animateTo(index),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 标签文本
          Text(
            title,
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: fontWeight,
              color: textColor,
            ),
          ),
          SizedBox(height: 6.h),
          // 指示器
          Container(
            height: 4.h,
            width: 10.w,
            decoration: BoxDecoration(
              color: Color.lerp(
                Colors.transparent,
                Colors.white,
                selectedPercent,
              ),
              borderRadius: BorderRadius.circular(1.5.r),
            ),
          ),
        ],
      ),
    );
  }

  // 构建私聊列表
  Widget _buildPrivateChatList() {
    return Obx(() {
      if (controller.privateChats.isEmpty) {
        return Center(
          child: Text(
            'No private chats',
            style: TextStyle(color: Colors.white70, fontSize: 16.sp),
          ),
        );
      }

      return ListView.builder(
        padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
        itemCount: controller.privateChats.length,
        itemBuilder: (context, index) {
          final chatRoom = controller.privateChats[index];
          final otherUser = controller.getPrivateChatUser(chatRoom);
          final unreadCount = controller.unreadCounts[chatRoom.id!] ?? 0;

          return _buildChatItem(
            avatar: otherUser?.avatar,
            name: otherUser?.nickname ?? otherUser?.username ?? 'User',
            lastMessage: chatRoom.lastMessage ?? 'No messages yet',
            unreadCount: unreadCount,
            onTap: () => controller.enterChatRoom(chatRoom),
          );
        },
      );
    });
  }

  // 构建群聊列表
  Widget _buildGroupChatList() {
    return Obx(() {
      if (controller.groupChats.isEmpty) {
        return Center(
          child: Text(
            'No group chats',
            style: TextStyle(color: Colors.white70, fontSize: 16.sp),
          ),
        );
      }

      return ListView.builder(
        padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
        itemCount: controller.groupChats.length,
        itemBuilder: (context, index) {
          final chatRoom = controller.groupChats[index];
          final unreadCount = controller.unreadCounts[chatRoom.id!] ?? 0;

          return _buildChatItem(
            groupChat: chatRoom,
            name: chatRoom.name,
            lastMessage: chatRoom.lastMessage ?? 'No messages yet',
            unreadCount: unreadCount,
            onTap: () => controller.enterChatRoom(chatRoom),
          );
        },
      );
    });
  }

  // 构建关注列表
  Widget _buildFollowList() {
    return Obx(() {
      if (controller.followingUsers.isEmpty) {
        return Center(
          child: Text(
            'No following users',
            style: TextStyle(color: Colors.white70, fontSize: 16.sp),
          ),
        );
      }

      return ListView.builder(
        padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
        itemCount: controller.followingUsers.length,
        itemBuilder: (context, index) {
          final user = controller.followingUsers[index];

          return _buildUserItem(
            avatar: user.avatar,
            name: user.nickname ?? user.username ?? 'User',
            onTap: () {
              // 跳转到用户页面
              Get.toNamed(
                Routes.me,
                arguments: {'userId': user.id, 'fromNavBar': false},
              );
            },
            actionButton: Container(
              height: 30.h,
              padding: EdgeInsets.symmetric(horizontal: 12.w),
              decoration: BoxDecoration(
                border: Border.all(color: Colors.white, width: 1),
                borderRadius: BorderRadius.circular(15.r),
              ),
              child: TextButton(
                onPressed: () => controller.unfollowUser(user.id!),
                style: TextButton.styleFrom(
                  padding: EdgeInsets.zero,
                  minimumSize: Size.zero,
                  tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                ),
                child: Text(
                  'Followed',
                  style: TextStyle(color: Colors.white, fontSize: 12.sp),
                ),
              ),
            ),
          );
        },
      );
    });
  }

  // 构建粉丝列表
  Widget _buildFanList() {
    return Obx(() {
      if (controller.followers.isEmpty) {
        return Center(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(
                Images.empty,
                width: 60.w,
                height: 76.h,
                fit: BoxFit.cover,
              ),
              SizedBox(height: 10.h),
              Text(
                'No fans yet',
                style: TextStyle(color: Colors.white70, fontSize: 16.sp),
              ),
              SizedBox(height: 100.h),
            ],
          ),
        );
      }

      return ListView.builder(
        padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
        itemCount: controller.followers.length,
        itemBuilder: (context, index) {
          final user = controller.followers[index];

          return FutureBuilder<bool>(
            future: controller.isFollowing(user.id!),
            builder: (context, snapshot) {
              final isFollowing = snapshot.data ?? false;

              return _buildUserItem(
                avatar: user.avatar,
                name: user.nickname ?? user.username ?? 'User',
                onTap: () {
                  // 跳转到用户页面
                  Get.toNamed(
                    Routes.me,
                    arguments: {'userId': user.id, 'fromNavBar': false},
                  );
                },
                actionButton: Container(
                  height: 30.h,
                  padding: EdgeInsets.symmetric(horizontal: 12.w),
                  decoration: BoxDecoration(
                    color:
                        isFollowing
                            ? Colors.transparent
                            : const Color(0xFF4580DD),
                    border:
                        isFollowing
                            ? Border.all(color: Colors.white, width: 1)
                            : null,
                    borderRadius: BorderRadius.circular(15.r),
                  ),
                  child: TextButton(
                    onPressed: () {
                      if (isFollowing) {
                        controller.unfollowUser(user.id!);
                      } else {
                        controller.followUser(user.id!);
                      }
                    },
                    style: TextButton.styleFrom(
                      padding: EdgeInsets.zero,
                      minimumSize: Size.zero,
                      tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    ),
                    child: Text(
                      isFollowing ? 'Followed' : 'Back',
                      style: TextStyle(color: Colors.white, fontSize: 12.sp),
                    ),
                  ),
                ),
              );
            },
          );
        },
      );
    });
  }

  // 构建聊天项
  Widget _buildChatItem({
    String? avatar,
    ChatRoom? groupChat,
    required String name,
    required String lastMessage,
    required int unreadCount,
    required VoidCallback onTap,
  }) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onTap,
        splashColor: Colors.white.withOpacity(0.1),
        highlightColor: Colors.white.withOpacity(0.05),
        child: Container(
          padding: EdgeInsets.symmetric(vertical: 10.h),
          child: Row(
            children: [
              // 头像
              groupChat != null
                  ? _buildGroupAvatar(groupChat)
                  : _buildAvatar(avatar),

              SizedBox(width: 15.w),

              // 名称和最后一条消息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      name,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w600,
                        fontFamily: 'Inter',
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    SizedBox(height: 4.h),
                    Text(
                      lastMessage,
                      style: TextStyle(
                        color: Colors.white70,
                        fontSize: 14.sp,
                        fontFamily: 'Inter',
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),

              // 未读消息数
              if (unreadCount > 0)
                Container(
                  width: 24.w,
                  height: 24.w,
                  decoration: BoxDecoration(
                    color: Colors.red,
                    shape: BoxShape.circle,
                  ),
                  child: Center(
                    child: Text(
                      unreadCount > 99 ? '99+' : unreadCount.toString(),
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 12.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }

  // 构建用户项
  Widget _buildUserItem({
    String? avatar,
    required String name,
    required VoidCallback onTap,
    Widget? actionButton,
  }) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onTap,
        splashColor: Colors.white.withOpacity(0.1),
        highlightColor: Colors.white.withOpacity(0.05),
        child: Container(
          padding: EdgeInsets.symmetric(vertical: 10.h),
          child: Row(
            children: [
              // 头像
              _buildAvatar(avatar),

              SizedBox(width: 15.w),

              // 名称
              Expanded(
                child: Text(
                  name,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                  ),
                  overflow: TextOverflow.ellipsis,
                ),
              ),

              // 操作按钮
              if (actionButton != null) actionButton,
            ],
          ),
        ),
      ),
    );
  }

  // 构建单个头像
  Widget _buildAvatar(String? avatar) {
    return Container(
      width: 50.w,
      height: 50.w,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        border: Border.all(color: Colors.white, width: 1.w),
      ),
      child: ClipOval(
        child:
            avatar != null && avatar.isNotEmpty
                ? (avatar.startsWith('assets/')
                    ? Image.asset(avatar, fit: BoxFit.cover)
                    : Image.file(
                      File(avatar),
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) {
                        return Image.asset(Images.avatar1, fit: BoxFit.cover);
                      },
                    ))
                : Image.asset(Images.avatar1, fit: BoxFit.cover),
      ),
    );
  }

  // 构建群聊头像
  Widget _buildGroupAvatar(ChatRoom chatRoom) {
    return Container(
      width: 50.w,
      height: 50.w,
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          // Container(
          //   width: 50.w,
          //   height: 50.w,
          //   decoration: BoxDecoration(
          //     shape: BoxShape.circle,
          //     border: Border.all(color: Colors.white, width: 1.w),
          //     color: const Color(0xFF305CA9),
          //   ),
          // ),

          // 最多显示3个成员头像
          if (chatRoom.memberIds.isNotEmpty)
            _buildGroupMemberAvatar(chatRoom, 0, Offset(0, 0)),
          if (chatRoom.memberIds.length > 1)
            _buildGroupMemberAvatar(chatRoom, 1, Offset(25.w, 0)),
          if (chatRoom.memberIds.length > 2)
            _buildGroupMemberAvatar(chatRoom, 2, Offset(0, 24.h)),

          // 右下角剩余人数
          chatRoom.memberIds.length > 4
              ? Positioned(
                right: 0,
                bottom: 0,
                child: Container(
                  width: 25.w,
                  height: 25.h,
                  decoration: BoxDecoration(
                    color: const Color(0xFF4169B8),
                    shape: BoxShape.circle,
                    border: Border.all(color: Colors.white, width: 1),
                  ),
                  child: Center(
                    child: Text(
                      '+${chatRoom.memberIds.length - 3}',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 10.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ),
              )
              : chatRoom.memberIds.length > 3
              ? _buildGroupMemberAvatar(chatRoom, 3, Offset(25.w, 25.h))
              : SizedBox(),
        ],
      ),
    );
  }

  // 构建群聊成员头像
  Widget _buildGroupMemberAvatar(ChatRoom chatRoom, int index, Offset offset) {
    // 如果索引超出成员数量，返回空容器
    if (index >= chatRoom.memberIds.length) {
      return Container();
    }

    // 获取用户ID
    final userId = chatRoom.memberIds[index];
    // 获取用户信息
    final user = controller.userCache[userId];

    return Positioned(
      left: offset.dx,
      top: offset.dy,
      child: Container(
        width: 25.w,
        height: 25.h,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          border: Border.all(color: Colors.white, width: 1),
          image: DecorationImage(
            image:
                user?.avatar != null && user!.avatar!.isNotEmpty
                    ? (user.avatar!.startsWith('assets/')
                        ? AssetImage(user.avatar!)
                        : FileImage(File(user.avatar!)) as ImageProvider)
                    : AssetImage(Images.avatar1),
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<NotificationController>(
      init: NotificationController(),
      id: "notification",
      builder: (_) {
        return Scaffold(
          body: SafeArea(top: false, bottom: false, child: _buildView()),
        );
      },
    );
  }
}
